import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;

//The servlet to display the items a user wants to buy
public class ShoppingCart extends HttpServlet
{
	private final static String REDIRECT_TO_LOGIN_CODE 
		= "<meta http-equiv=\"REFRESH\" content=\"2;url=../Login.jsp\">";
		
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		doGet(request, response);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		System.out.println("\n\n---==Doing GET in ShoppingCart==---\n");
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession();
		
		boolean reachedViaUpdateButton = false;
		if ( session.getAttribute(Constants.viaUpdateButtonAttributeName) != null &&
				((Boolean)session.getAttribute(Constants.viaUpdateButtonAttributeName)).booleanValue() )
		{
			reachedViaUpdateButton = true;
			session.removeAttribute(Constants.viaUpdateButtonAttributeName);
		}
		
		//get the cart, or make a new one if we need one
		CartOfItems cart = (CartOfItems)session.getAttribute(Constants.cartAttributeName);
		if (cart == null)
		{
			cart = new CartOfItems();
			System.out.println("The session cart hash code=[" + cart.hashCode() + "]. (initializing it)");
		}
		else
		{
			System.out.println("The session cart hash code=[" + cart.hashCode() + "]");			
		}
		cart = new CartOfItems(cart); //make a copy, so we don't change the stored cart before we want to
		
		System.out.println("The current cart hash code=[" + cart.hashCode() + "]");
		System.out.println("The current cart contains: " + cart);
		
		//if we came from a page where a DVD needs to be added, add it
		DVD dvdToAdd = (DVD)session.getAttribute(Constants.dvdToAddAttributeName);
		if (dvdToAdd != null)
		{
			cart.addDVD(dvdToAdd);
		}
		
		//if user is not logged in, send them to the login page
		String user = (String)session.getAttribute(Constants.loggedInUserAttributeName);
		if (user == null)
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_LOGIN_CODE + "</head>"
					+ "<body>You need to log in first...</body>" 
					+"</html>");
			return;
		}
		
		//if the user is updating the quantities in the cart, then do so
		ArrayList<DVD> dvdsToSet = (ArrayList<DVD>)session.getAttribute(Constants.dvdsToSetAttributeName);
		ArrayList<DVD> dvdsToRemove = new ArrayList<DVD>();
		System.out.println("In ShoppingCart: dvdsToSet=" + dvdsToSet);
		
		if (dvdsToSet != null)
		{
			for (int i = 0; i < dvdsToSet.size(); i++)
			{
				if (dvdsToSet.get(i).getQuantity() != 0)
					cart.setExistingDVD(dvdsToSet.get(i));
				else
					dvdsToRemove.add(dvdsToSet.get(i));
			}
		}
		
		//if the user is confirming a DVD removal, remove it/them
		System.out.println(buttonPushed(request));
		if (buttonPushed(request).equals("ConfirmButton"))
		{
			System.out.println("User hit the confirm button!");
			
			if (dvdsToRemove != null)
				for (int i = 0; i < dvdsToRemove.size(); i++)
				{
					cart.removeDvdWithId(dvdsToRemove.get(i).getID());
				}
			
			//store the cart back into the session
			session.setAttribute(Constants.cartAttributeName, cart);
			
			//we've set the dvds, so clear this list
			session.removeAttribute(Constants.dvdsToSetAttributeName);
			
			//we've removed the dvds to remove, so clear the list
			dvdsToRemove = new ArrayList<DVD>();
			
		}
		else if (!reachedViaUpdateButton) //user didn't confirm or initiate removal
		{
			System.out.println("User did NOT hit the confirm or update buttons.");
			//so we don't want to remove any dvds
			dvdsToRemove = new ArrayList<DVD>();
		}
		
		//clear the list of dvds to remove
		//session.removeAttribute(Constants.dvdsToRemoveAttributeName);
		
		
		//if the user has decided to remove a DVD, ask user to verify first
		System.out.println("dvdsToRemove:" + dvdsToRemove);
		if (dvdsToRemove.size() > 0)
		{
			StringBuffer buf = new StringBuffer("<h5>Are you sure you want to remove the " +
					"following films from your cart?</h5>");
			buf.append(printShoppingCart(dvdsToRemove, false, false));
			buf.append("<form name=\"ConfirmForm\" method=\"POST\" action=\"ShoppingCart\">");
			buf.append("<input type=\"image\" name=\"ConfirmButton\" width=\"143\" height=\"69\" src=\"../images/ConfirmButton.png\">");
			buf.append("</form>");
			buf.append("<form name=\"CancelForm\" method=\"POST\" action=\"ShoppingCart\">");
			buf.append("<input type=\"image\" name=\"CancelButton\" width=\"143\" height=\"69\" src=\"../images/CancelButton.png\">");
			buf.append("</form>");
			//session.setAttribute(Constants.dvdsToRemoveAttributeName, zeroQuantityDvds);
			out.print(Template.getTemplateHTML("Your Cart", buf.toString(), 
					Constants.udpateCartAndGoToCart, session));
		}
		else if ( getTotalQuantity(cart.getAllDvds()) <= 0 ) // the cart is empty
		{
			StringBuffer buf = new StringBuffer("<p><h3>Your cart is empty.</h3></p>");
			buf.append("<TABLE bgcolor=\"#FFFFFF\" border=0 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
			buf.append("<TR valign=top>");
			buf.append("<TD align=right width=450 height=76>");
			buf.append("<a href=\"../Search.jsp\">");
			buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/SearchEnd.png\"></div></a>");
			buf.append("</TD>");
			buf.append("<TD align=left width=450 height=76>");
			buf.append("<a href=\"../Browse.jsp\">");
			buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/BrowseEnd.png\"></div></a>");
			buf.append("</TD>");
			buf.append("</TR>");
			buf.append("</TABLE>");
			out.print(Template.getTemplateHTML("Your Cart", buf.toString(), 
					Constants.udpateCartAndGoToCart, session));
			
			//when we're done, be sure to store the cart back into the session
			session.setAttribute(Constants.cartAttributeName, cart);
			session.removeAttribute(Constants.dvdsToSetAttributeName);
		}
		else //show the user the cart
		{
			out.print(Template.getTemplateHTML("Your Cart", printShoppingCart(cart.getAllDvds(), true, true), 
					Constants.udpateCartAndGoToCart, session));
			
			//when we're done, be sure to store the cart back into the session
			session.setAttribute(Constants.cartAttributeName, cart);
			session.removeAttribute(Constants.dvdsToSetAttributeName);
		}
		
		
		session.removeAttribute(Constants.dvdToAddAttributeName);				
	}
	
	private String printShoppingCart(ArrayList<DVD> dvds, boolean showQuantities, boolean printButtons)
	{
		StringBuffer buf = new StringBuffer();
		
		//buf.append("<form name=\"cartForm\" action=\"DvdProcessor\" method=\"POST\">");
		//out.println("<div align=\"left\"><br>");
		
		//making table
	
		buf.append("<div><TABLE bgcolor=\"#FFFFFF\" border=1 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
		
		buf.append("<TR valign=top>");	
	
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>TITLE</B>");
		buf.append("</div>");
		buf.append("</TD>");		
		
		buf.append("<TD width=100><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>YEAR</B>");
		buf.append("</div>");
		buf.append("</TD>");
		
		buf.append("<TD width=150><div class=\"wpmd\">");
		buf.append("<div>");
		buf.append("<B>DIRECTOR</B>");
		buf.append("</div>");
		buf.append("</TD>");
		
		if (showQuantities)
		{
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append("<B>QUANTITY</B>");
			buf.append("</div>");
			buf.append("</TD>");
			buf.append("</TR>");
		}
		
		for (int i = 0; i < dvds.size(); i++)
		{
			//title
			buf.append("<TR valign=top>");
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getTitle() );
			buf.append("</div>");
			buf.append("</TD>");
			
			//year
			buf.append("<TD width=100><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getYear() );
			buf.append("</div>");
			buf.append("</TD>");
			
			//director's name
			buf.append("<TD width=150><div class=\"wpmd\">");
			buf.append("<div>");
			buf.append( dvds.get(i).getDirectorName() );
			buf.append("</div>");
			buf.append("</TD>");
			
			// quantity
			if (showQuantities)
			{
				buf.append("<TD width=150><div class=\"wpmd\">");
				buf.append("<div>");
				buf.append("<input name=\"" + dvds.get(i).id + "\" type=\"text\" value=\"" + dvds.get(i).getQuantity() + "\">" );
				buf.append("</div>");
				buf.append("</TD>");
			}
			
			buf.append("</TR>");
		}
		buf.append("</TABLE>");
		
		if (printButtons)
		{
			buf.append("<TABLE bgcolor=\"#FFFFFF\" border=0 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
			buf.append("<TR valign=top>");
			buf.append("<TD align=right width=300 height=76>");
			buf.append("<a href=\"../Search.jsp\">");
			buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/SearchEnd.png\"></div></a>");
			buf.append("</TD>");
			buf.append("<TD align=center width=300 height=76>");
			buf.append("<div id=\"enter\" \"><input type=\"image\" name=\"UpdateButton\" src=\"../images/UpdateCart.png\"></div>");
			buf.append("</TD>");
			buf.append("<TD align=left width=300 height=76>");
			buf.append("<a href=\"../Browse.jsp\">");
			buf.append("<div id=\"Next\" \"><input type=\"image\" name=\"Next\" src=\"../images/BrowseEnd.png\"></div></a>");
			buf.append("</TD>");
			buf.append("</TR>");
			buf.append("</TABLE>");
		}
		
		//buf.append("<TR valign=top>");
	
		//buf.append("<TD align=right colspan=5><div class=\"wpmd\">");
		//buf.append("<div id=\"enter\" \"><input type=\"image\" name=\"UpdateButton\" src=\"../images/UpdateCart.png\"></div>");
		//buf.append("</TD>");
		//buf.append("</TR>");
		
		//buf.append("</TABLE>");

		buf.append("</form>");
		
		return buf.toString();
	}
	
	private int getTotalQuantity(ArrayList<DVD> dvds)
	{
		int total = 0;
		
		for (int i = 0; i < dvds.size(); i++)
		{
			total += dvds.get(i).getQuantity();
		}
		
		return total;
	}
	
	private String buttonPushed(HttpServletRequest request)
	{
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements())
		{
			String param = paramNames.nextElement();
			if(param.endsWith(".x"))
				return param.substring( 0, param.length() - 2 );
		}
		
		return "none";
	}
}